package com.smart.service.impl;

import com.smart.pojo.Permission;
import com.smart.mapper.PermissionMapper;
import com.smart.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lyj
 * @since 2023-04-19
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public List<Permission> queryByRoleId(Long roleId) {
        return baseMapper.queryByRoleId(roleId);
    }

    @Override
    public List<Permission> queryByUserId(Long userId) {
        List<Permission> userPermissions = (List<Permission>) redisTemplate.opsForHash().get("permission", userId);
        List<Permission> publicPermissions = (List<Permission>) redisTemplate.opsForHash().get("permission", "public");
        if (userPermissions == null || publicPermissions == null || userPermissions.isEmpty() || publicPermissions.isEmpty()) {
            System.out.println("Redis缓存中无该用户的对应权限缓存");

            List<Permission> userPermissionList = baseMapper.queryByUserId(userId);
            redisTemplate.opsForHash().put("permission", userId, userPermissionList);
            List<Permission> publicPermissionList = this.lambdaQuery().eq(Permission::getIsPublic, 1).list();
            redisTemplate.opsForHash().put("permission", "public", publicPermissionList);
            userPermissionList.addAll(publicPermissionList);

            return userPermissionList;
        } else {
            userPermissions.addAll(publicPermissions);
            return userPermissions;
        }
    }

    @Override
    @Transactional
    public boolean saveOrUpdatePermission(Permission permission) {
        if (permission.getIsPublic() == 1) {
            redisTemplate.opsForHash().delete("permission", "public");
        }
        return this.saveOrUpdate(permission);
    }
}
